package beautiful.butterfly.drds.schedule.task.schedule_manager;

import beautiful.butterfly.drds.schedule.ScheduleUtil;
import beautiful.butterfly.drds.schedule.cron_expression.CronExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Timer;

/**
 * Created by ibm on 2018/1/20.
 */
class PauseOrResumeTask extends java.util.TimerTask {
    private static transient Logger log = LoggerFactory
            .getLogger(HeartBeatTimerTask.class);
    public static int TYPE_PAUSE = 1;
    public static int TYPE_RESUME = 2;
    Manager manager;
    Timer timer;
    int type;
    String cronTabExpress;

    public PauseOrResumeTask(Manager aManager, Timer aTimer, int aType, String aCronTabExpress) {
        this.manager = aManager;
        this.timer = aTimer;
        this.type = aType;
        this.cronTabExpress = aCronTabExpress;
    }

    public void run() {
        try {
            Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
            this.cancel();//ȡ����������
            Date current = new Date(System.currentTimeMillis());
            CronExpression cexp = new CronExpression(this.cronTabExpress);
            Date nextTime = cexp.getNextValidTimeAfter(current);
            if (this.type == TYPE_PAUSE) {
                manager.pause("������ֹʱ��,pause����");
                this.manager.getScheduleServer().setNextRunEndTime(ScheduleUtil.transferDataToString(nextTime));
            } else {
                manager.resume("���￪ʼʱ��,resume����");
                this.manager.getScheduleServer().setNextRunStartTime(ScheduleUtil.transferDataToString(nextTime));
            }
            this.timer.schedule(new PauseOrResumeTask(this.manager, this.timer, this.type, this.cronTabExpress), nextTime);
        } catch (Throwable ex) {
            log.error(ex.getMessage(), ex);
        }
    }
}
